//
//  SIXMessageController.m
//  weibo
//
//  Created by chenangel on 16/5/20.
//  Copyright © 2016年 chuhan. All rights reserved.
//

#import "SIXMessageController.h"
#import "SIXFieldView.h"
#import "SIXFindTableController.h"
#import "SIXChatViewController.h"
#import "SIXPPresentationController.h"
#import "SIXBasicTableViewController.h"
#import "SIXSearchTableViewController.h"
#import "AFNetworking.h"
#import "SIXApiTestController.h"
#import "SIXAccount.h"
#import "SIXAccountTool.h"
#import "MJExtension.h"
#import "SIXMessModel.h"
#import "SIXMessTableViewCell.h"



@interface SIXMessageController ()<UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning,UITextFieldDelegate>
/// 记录是否弹出
@property (nonatomic, assign)BOOL isPresented;

@property (nonatomic, weak)UIView *toView;

@property(nonatomic,strong)UIView *fieldView;

@property(nonatomic,strong)NSMutableArray *MessModel;
@property(nonatomic,strong)UIView *fromView;

@end

@implementation SIXMessageController

static NSString *ID = @"mess";

-(NSMutableArray *)MessModel{
    
    if (_MessModel == nil) {
        
        _MessModel = [NSMutableArray array];
       
    }
    
    return _MessModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //调用消息导航栏内容设置方法
    [self setNavgation];
    //给cell复用添加重要标示
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:ID];
    [self.tableView registerNib:[UINib nibWithNibName:@"MessCell" bundle:nil] forCellReuseIdentifier:@"Mess"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self get];
}


-(void)get{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //封装参数
    SIXAccount *acount = [SIXAccountTool account];
    NSDictionary *dict = @{
                           
                           @"access_token" : acount.access_token,
                           @"uid" : acount.uid
                           
                           };
       [manager GET:@"https://api.weibo.com/2/friendships/friends/in_common.json"parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
           [responseObject writeToFile:@"/Users/lixiaoyun/Desktop/dict.plist" atomically:YES];
           NSArray *array = responseObject[@"users"];
           
           [SIXMessModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
               
                    return @{@"descriptions":@"description"};
           }];
 
           for (NSDictionary *dict in array) {

               SIXMessModel *model = [SIXMessModel mj_objectWithKeyValues:dict];
     
               [self.MessModel addObject:model];
           }

              [self.tableView reloadData];

           } failure:^(NSURLSessionDataTask *task, NSError *error) {

          }];
    
}
-(void)setNavgation{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
    dict[NSForegroundColorAttributeName] = [UIColor grayColor];
    [self.navigationController.navigationBar setTitleTextAttributes:dict];
    //设置消息导航栏内容
    self.navigationItem.title = @"消息";
    //设置消息左边按钮
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"发现群" forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    [leftBtn sizeToFit];
    [leftBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //设置消息右边按钮
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"navigationbar_icon_newchat"] forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:@"navigationbar_icon_newchat_highlight"] forState:UIControlStateHighlighted];
    [rightBtn addTarget:self action:@selector(rightBtnClcik:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}

#pragma mark - 按钮监听事件
/**
 *  监听左边按钮点击事件
 */
-(void)leftBtnClick:(UIBarButtonItem *)leftBtn{
    
    SIXFindTableController *findVC = [[SIXFindTableController alloc]init];
    [self.navigationController pushViewController:findVC animated:YES];

}


/**
 *  监听右边按钮点击事件
 */
-(void)rightBtnClcik:(UIBarButtonItem *)rightBtn{
    //右边按钮为自定义转场动画
    UIStoryboard *storyboard = [UIStoryboard  storyboardWithName:@"MessageChat" bundle:nil];
    SIXChatViewController *chatVC = [storyboard instantiateInitialViewController];

    chatVC.transitioningDelegate = self;
    chatVC.modalPresentationStyle = UIModalPresentationCustom;
    
    [self presentViewController:chatVC animated:YES completion:nil];
    
}

#pragma mark tableView -代理和数据源方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.MessModel.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row<= 2) {
       
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        if (indexPath.row == 0) {
            cell.imageView.image = [UIImage imageNamed:@"messagescenter_at"];
            cell.textLabel.text = @"@我的";
            
        }
        if (indexPath.row == 1) {
            cell.imageView.image = [UIImage imageNamed:@"messagescenter_comments"];
            cell.textLabel.text = @"评论";
            
        }
        if (indexPath.row == 2) {
            cell.imageView.image = [UIImage imageNamed:@"messagescenter_good"];
            cell.textLabel.text = @"赞";
            
        }
        
        return cell;
    }else{
        
        SIXMessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Mess"];
        
        cell.Messmodel = self.MessModel[indexPath.row-3];

        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 55;
    
}
//返回头部视图,并监听头部视图的点击事件
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    SIXFieldView *fieldView = [SIXFieldView SixFieldView];
    
    for (UITextField *Field in fieldView.subviews) {
        
        if ([Field isKindOfClass:[UITextField class]]) {
            
            Field.delegate = self;
            
    };
}
     return fieldView;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MessageSearch" bundle:nil];
    SIXSearchTableViewController *searchVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:searchVC animated:YES completion:nil];
    return NO;
}
//返回头部视图的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40;

}
//监听cell的点击事件
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //获取当前点击的cell
//    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//    UITableViewController *cellVC = [[UITableViewController alloc]init];
//    
}

#pragma mark - <UIViewControllerTransitioningDelegate>
/// 该代理方法用于返回负责转场的控制器对象
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source{
    return  [[SIXPPresentationController alloc]initWithPresentedViewController:presented presentingViewController:presenting];
}
/// 该代理方法用于告诉系统谁来负责控制器如何弹出
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    self.isPresented = YES; //记录弹回
    return self;
}
/// 该代理方法用于告诉系统谁来负责控制器如何消失
- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    self.isPresented = NO; //记录弹出
    return self;
}

#pragma mark - <UIViewControllerAnimatedTransitioning>
- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    
    _fromView = fromView;
    return  998;
}


//动画执行
//(传一个遵守<UIViewControllerContextTransitioning>协议的transitionContext对象(UIViewControllerTransitioning(分类) 的代理)给你,这个协议里面有容器视图,停止动画的这些方法)
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    // 1.判断当前是弹出还是消失
    if (self.isPresented) {
        // 弹出
        [self animatePresentedController:transitionContext];
    }else {
        // 消失
        [self animateDismissedController:transitionContext];
    }
    
}

//自定义弹出动画
- (void)animatePresentedController:(id <UIViewControllerContextTransitioning>)transitionContext{
//    self.cityButton.selected = !self.cityButton.selected;
    //1.拿到弹出的视图
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    _toView = toView;
    
    // 2.将被弹出的控制器View添加到容器视图上
    [[transitionContext containerView]addSubview:toView];
    
    
    //3.执行动画
    toView.transform = CGAffineTransformMakeScale(1, 0.01);
    toView.layer.anchorPoint = CGPointMake(0.5, 0);
    
    [UIView animateWithDuration:0.5 animations:^{
        toView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
    
    
}
//自定义关闭动画
- (void)animateDismissedController:(id <UIViewControllerContextTransitioning>)transitionContext{
    
    //1.拿到弹出的视图
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    
//    _fromView = fromView;
    // 2.将被弹出的控制器View添加到容器视图上
    [[transitionContext containerView]addSubview:fromView];
    
    // 3.执行动画
    fromView.layer.anchorPoint = CGPointMake(0.5, 0);
    
    
    [UIView animateWithDuration:0.1 animations:^{
        [fromView removeFromSuperview];
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
        
    }];
    
    
}

-(void)viewWillDisappear:(BOOL)animated{
    
    if (_fromView != nil) {
        
        [_fromView removeFromSuperview];
    }
    
    [super viewWillDisappear:animated];
}

@end
